using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.XPath;

namespace Pegasus.Microsoft.Office.Excel
{
	/// <summary>
	/// Summary description for PdxSettings.
	/// </summary>
	public class XmlExcel : IEnumerable
	{
		// Local Instance Values
		private Hashtable m_worksheets = new Hashtable();

		/// <summary>Microsoft Office SpreadSheet namespace</summary>
		public const string NAMESPACE_SPREADSHEET = "urn:schemas-microsoft-com:office:spreadsheet";

		/// <summary>
		/// Default Constructor.
		/// </summary>
		public XmlExcel()
		{
		}

		/// <summary>
		/// 
		/// </summary>
		public int Count
		{
			get
			{
				return m_worksheets.Count;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public XmlWorksheet this[ int x ]
		{
			get
			{
				if( m_worksheets.Count > x )
				{
					int count = 0;
					foreach( XmlWorksheet worksheet in m_worksheets.Values )
					{
						if( count == x )
						{
							return worksheet;
						}

						count++;
					}
				}
				else
				{
					throw new IndexOutOfRangeException( "Index out of range" );
				}
				
				return null;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public XmlWorksheet this[ string name ]
		{
			get
			{
				return (XmlWorksheet) m_worksheets[ name ];
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Load( string xmlFilename )
		{
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load( xmlFilename );
			
			Load( xmlDoc );
		}
			
		/// <summary>
		/// 
		/// </summary>
		public void Load( Stream xmlStream )
		{
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load( xmlStream );

			Load( xmlDoc );
		}

		/// <summary>
		/// 
		/// </summary>
		public void Load( XmlDocument xmlDocument )
		{
			XPathNavigator xmlDocNav = xmlDocument.CreateNavigator();

			XPathNodeIterator worksheetIter = xmlDocNav.SelectDescendants( "Worksheet", NAMESPACE_SPREADSHEET, false );
			while( worksheetIter.MoveNext() )
			{
				XmlWorksheet worksheet = new XmlWorksheet( worksheetIter.Current );
				m_worksheets.Add( worksheet.Name, worksheet );
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public IEnumerator GetEnumerator()
		{
			return m_worksheets.Values.GetEnumerator();
		}
	}
}
